import os
import cv2
import numpy as np
from commonFunctions import *


# 获取卡片中心圆的位置 & 半径
def get_card_center_point(_img, _debug=False):
    _h, _w = get_HW(_img)
    _h_center = _h // 2
    _w_center = _w // 2
    _gray = to_gray(_img)
    _circles1 = cv2.HoughCircles(_gray, cv2.HOUGH_GRADIENT, 1,
                                 600, param1=100, param2=30, minRadius=30, maxRadius=100)
    _circles = np.uint16(np.around(_circles1[0, :, :]))
    _center = None
    _circles = sorted(_circles, key=lambda x: (x[0] - _w_center) ** 2 + (x[1] - _h_center) ** 2)
    if len(_circles) > 0:
        for i in _circles[:1]:
            _center = i
            _cx, _cy, _r = i[0], i[1], i[2]
            if int(0.1 * _w) < _cx < int(0.9 * _w) and int(0.1 * _h) < _cy < int(0.9 * _h):
                # if _debug:
                cv2.circle(_img, (_cx, _cy), _r, (255, 0, 0), 5)
                cv2.circle(_img, (_cx, _cy), 2, (255, 0, 255), 10)
                cv2.rectangle(_img, (_cx - _r, _cy + _r), (_cx + _r, _cy - _r),
                              (255, 255, 0), 5)
    if isinstance(_center, type(None)):
        return _w // 2, _h // 2, 0
    else:
        return int(_center[0]), int(_center[1]), int(_center[2])


if __name__ == '__main__':
    root = r"E:\BaiduDisk\500"
    names = os.listdir(root)
    for name in names:
        img_path = r"E:\BaiduDisk\500\\" + name
        # img_path = r"E:\BaiduDisk\500\IMG_20210918_235116.jpg"
        img = cv2.imread(img_path)
        img = to_resize(img, 4)
        cx, cy = get_card_center_point(img)
        get_showimage(img)
